package org.example.easybuy.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeRefundModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpResponse;
import org.example.easybuy.entity.Order;
import org.example.easybuy.service.OrderService;
import org.example.easybuy.util.CustomResult;
import org.example.easybuy.util.PaymentProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;

@RequestMapping("/alipay")
@RestController
public class PaymentController {

    @Autowired
    private OrderService orderService;
    ObjectMapper objectMapper=new ObjectMapper();

    @RequestMapping("/payment")
    public void pay(int id , HttpServletResponse response) throws IOException, AlipayApiException {
        //阿里支付客户端对象
        AlipayClient alipayClient=new DefaultAlipayClient(PaymentProperties.getGateway(),PaymentProperties.getAppId(),
                                PaymentProperties.getPrivateKey(),"json",PaymentProperties.charset,PaymentProperties.getPublicKey(),
                                PaymentProperties.sign_type);
        //统一支付请求对象
        AlipayTradePagePayRequest payRequest=new AlipayTradePagePayRequest();
        //设置异步和回调的路径
        payRequest.setNotifyUrl(PaymentProperties.getNotify_url());
        payRequest.setReturnUrl(PaymentProperties.getReturn_url());
        //根据订单id查出该订单
        Order order=orderService.selectOrderById(id);
        //设置四个必须参数
        Map<String,Object> map=new HashMap<>();
        map.put("out_trade_no",order.getSerialNumber());
        map.put("total_amount",order.getCost());
        map.put("subject",order.getLoginName()+"的订单"+order.getId());
        map.put("product_code","FAST_INSTANT_TRADE_PAY");
        //使用jackson将map转化为json格式
        payRequest.setBizContent(objectMapper.writeValueAsString(map));
        //获取返回的html片段
        String result=alipayClient.pageExecute(payRequest).getBody();
        //将html片段响应回去
        response.setContentType("text/html");
        response.setCharacterEncoding("utf-8");
        PrintWriter pw=response.getWriter();
        pw.write(result);
        pw.flush();
        pw.close();
    }

    @RequestMapping("/notify_url")
    public void notify_url(HttpServletRequest request, HttpServletResponse response) throws IOException, AlipayApiException {
        System.out.println("异步回调开始执行");
        //获取支付宝POST过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        System.out.println("================" + objectMapper.writeValueAsString(requestParams));

        boolean signVerified = AlipaySignature.rsaCheckV1(params, PaymentProperties.getPublicKey(), PaymentProperties.charset, PaymentProperties.sign_type); //调用SDK验证签名

        //——请在这里编写您的程序（以下代码仅作参考）——

	/* 实际验证过程建议商户务必添加以下校验：
	1、需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号，
	2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额），
	3、校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email）
	4、验证app_id是否为该商户本身。
	*/
        response.setContentType("text/html");
        response.setCharacterEncoding("UTF-8");
        //给支付宝响应
        PrintWriter out = response.getWriter();
        out.println("<h1>支付完成  异步</h1>");
        if (signVerified) {//验证成功
            //商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");

            //支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");

            //交易状态
            String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"), "UTF-8");

            if (trade_status.equals("TRADE_FINISHED")) {
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //如果有做过处理，不执行商户的业务程序

                //注意：
                //退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
                System.out.println("交易关闭！");
            } else if (trade_status.equals("TRADE_SUCCESS")) {
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //如果有做过处理，不执行商户的业务程序
                Order order=new Order();
                //更改支付状态
                order.setIsPay(1);
                order.setSerialNumber(out_trade_no);
                //保存交易号
                order.setTrade_no(trade_no);
                orderService.updateOrderBySerial(order);
                //注意：
                //付款完成后，支付宝系统发送该交易状态通知
                System.out.println("付款完成！");
            }
            //给支付宝响应success否则将继续加载异步回调
            out.println("success");

        } else {//验证失败
            out.println("fail");
            System.out.println("验证失败");
            //调试用，写文本函数记录程序运行情况是否正常
            //String sWord = AlipaySignature.getSignCheckContentV1(params);
            //PaymentProperties.logResult(sWord);
        }
        out.close();
        System.out.println("异步回调执行完成");

    }

    @RequestMapping("/return_url")
    public void return_url(HttpServletRequest request, HttpServletResponse response) throws IOException, AlipayApiException {
        System.out.println("同步回调执行");
        //获取支付宝GET过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        System.out.println("================" + objectMapper.writeValueAsString(requestParams));
        //调用SDK验证签名
        boolean signVerified = AlipaySignature.rsaCheckV1(params, PaymentProperties.getPublicKey(), PaymentProperties.charset, PaymentProperties.sign_type);

        //——请在这里编写您的程序（以下代码仅作参考）——
        response.setContentType("text/html");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        out.println("<h1>支付完成</h1>");

        signVerified = true;
        if (signVerified) {
            //商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");

            //支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");

            //付款金额
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8");
//            out.println("<script>alert(\"支付宝交易号:\" + trade_no + \"<br/>商户订单号:\" + out_trade_no + \"<br/>付款金额:\" + total_amount)</script>");
            out.println("支付宝交易号:" + trade_no + "<br/>商户订单号:" + out_trade_no + "<br/>付款金额:" + total_amount+"<a href='http://localhost:8080/api/Member_order.html'>返回</a>");
        } else {
            out.println("验签失败");
        }

        out.close();
    }

    @RequestMapping("/backFor")
    public CustomResult backFor(String cost, String serialNumber) throws AlipayApiException, JsonProcessingException {
        AlipayClient alipayClient=new DefaultAlipayClient(PaymentProperties.getGateway(),PaymentProperties.getAppId(),PaymentProperties.getPrivateKey(),
                "json",PaymentProperties.charset,PaymentProperties.getPublicKey(),PaymentProperties.sign_type);
        AlipayTradeRefundRequest refundRequest=new AlipayTradeRefundRequest();
        AlipayTradeRefundModel refundModel=new AlipayTradeRefundModel();
        refundModel.setOutTradeNo(serialNumber);
        refundModel.setRefundAmount(cost);
        refundModel.setOutRequestNo(UUID.randomUUID().toString());
        refundRequest.setBizModel(refundModel);
        AlipayTradeRefundResponse refundResponse=alipayClient.execute(refundRequest);
        if(refundResponse.isSuccess())
        {
            if(refundResponse.getFundChange().equals("Y"))
            {
                CustomResult customResult=CustomResult.successResult();
                Order order=new Order();
                //更改支付状态
                order.setIsPay(3);
                order.setSerialNumber(serialNumber);
                //保存交易号
                order.setRefund_no(refundModel.getOutRequestNo());
                orderService.updateOrderBySerial(order);
                customResult.addResult("status","success");
                return customResult;
            }else{
                return CustomResult.errorResult(500,"该订单已退款");
            }

        }else{
            return CustomResult.errorResult(500,"退款出错");
        }
    }

}
